﻿/****************
* Authored by Zhuo "Wizcas" Chen
* 2018 © Wubi.fun all rights reserved
*****************/

using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ResPopper : MonoBehaviour
{
    static ResPopper _instance;
    public static ResPopper instance { get { return _instance ?? (_instance = FindObjectOfType<ResPopper>()); } }

    [SerializeField] PopSettings _popSettings;
    [SerializeField] ResItem _itemPrefab;
    [SerializeField] Text _tipPrefab;
    [SerializeField] float _interval;

    RectTransform rectTransform { get { return transform as RectTransform; } }
    Dictionary<int, int> _stackPopCounter = new Dictionary<int, int>();

    public void Pop(Res res, BlockStack stack)
    {
        var uiPos = UIHelper.WorldToUIPos(stack.topPos, rectTransform);
        var item = Instantiate(_itemPrefab, transform);

        int counter = 0;
        if (!_stackPopCounter.ContainsKey(stack.id)) { _stackPopCounter[stack.id] = 1; }
        else { counter = _stackPopCounter[stack.id]++; }
        item.Pop(res, uiPos, counter, _popSettings).OnComplete(() => _stackPopCounter[stack.id]--);
    }

    public void PopTip(string text, BlockStack stack, Color color)
    {
        var uiPos = UIHelper.WorldToUIPos(stack.topPos, rectTransform);
        var tip = Instantiate(_tipPrefab, transform);
        tip.text = text;
        tip.color = Color.clear;
        
        tip.rectTransform.anchoredPosition = uiPos;
        DOTween.Sequence()
            .AppendCallback(() => tip.color = color)
            .Join(tip.rectTransform.DOAnchorPosY(uiPos.y + _popSettings.upY, _popSettings.popTime).SetEase(Ease.OutSine))
            .Join(tip.DOFade(0, _popSettings.fadeTime).SetDelay(_popSettings.fadeDelay))
            .AppendCallback(() => Destroy(tip.gameObject));
    }
}

[System.Serializable]
public class PopSettings
{
    public float upY = 80;
    public float popTime = 1f;
    public float fadeDelay = .7f;
    public float fadeTime = .5f;
    public float interval = .5f;
}